package com.bangdao.app.jetpacktest.jetpack.viewmodel;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.widget.TextView;

import com.bangdao.app.jetpacktest.R;

public class TimerActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timer);

        initComponent();
    }

    private void initComponent() {
        final TextView tvTime = findViewById(R.id.tvTime);
        //ViewModel的实例化过程，是通过ViewModelProvider来完成的。ViewModelProvider会判断ViewModel是否存在，若存在则直接返回，否则它会创建一个ViewModel。
        TimerViewModel timerViewModel = new ViewModelProvider(this).get(TimerViewModel.class);
        timerViewModel.setOnTimeChangeListener(new TimerViewModel.OnTimeChangeListener() {
            @Override
            public void onTimeChanged(int second) {
                //更新UI界面
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvTime.setText("TIME:" + second);
                    }
                });
            }
        });
        timerViewModel.startTiming();
    }
}